import './index.scss'
import {useEffect, useState} from "react";
import {createPortal} from 'react-dom'
import classnames from 'classnames'

export interface BaseModalProps {
  show: boolean,
  onClose?: () => any,
  children?: any
}

export default function Modal(props: BaseModalProps) {
  const {show, onClose, children} = props
  const [display, setDisplay] = useState(false)

  const cls = classnames('modal', {
    in: show,
    out: !show
  })

  function animationendHandler() {
    if (!show) {
      setDisplay(false)
    }
  }

  useEffect(() => {
    show && setDisplay(true)
  }, [show])

  if (!display) { return null }

  return (
    <>
    {
      createPortal(
        <div 
          className={cls} 
          onAnimationEnd={animationendHandler} 
          onClick={onClose}
        >
          {children}
        </div>,
        document.body
      )
    }
    </>
    
  )
}
